<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="800px"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        :disabled="!canEdit"
        v-loading="loading"
      >
        <el-form-item label="车间编码" prop="workshopCode">
          <el-input
            type="text"
            v-model="form.workshopCode"
            placeholder="请输入车间编码"
            :disabled="!!form.id"
          ></el-input>
          <el-switch
            v-model="systemNumber"
            active-text="系统编号"
            class="system-num"
            :disabled="!!form.id"
            @change="handleGetCode"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="车间名称" prop="workshopName">
          <el-input
            type="text"
            v-model="form.workshopName"
            placeholder="请输入车间名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="车间类型" prop="workshopType">
          <el-select
            v-model="form.workshopType"
            placeholder="请选择车间类型"
            size="small"
          >
            <el-option
              v-for="item in dict.workshopType"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属工厂" prop="factoryDeptCode">
          <organizationSelect
            ref="orgSelect"
            v-model="form.factoryDeptCode"
            :onlyFactory="true"
            class="factory-select"
            @change="handleFactoryDeptCodeChange"
          ></organizationSelect>
        </el-form-item>
        <el-form-item label="车间负责人" prop="workshopHeadRealnames">
          <el-input
            v-model="form.workshopHeadRealnames"
            placeholder="请选择车间负责人"
            size="small"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="openUserDialog()"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item
          label="包含产线"
          prop="productionLineDtos"
          style="width: 100%"
        >
          <el-select
            v-model="form.productionLineDtos"
            placeholder="请选择产线"
            size="small"
            multiple
          >
            <el-option
              v-for="item in productionLineOptions"
              :key="item.erpProductionLineCode"
              :label="item.erpProductionLineName"
              :value="item.erpProductionLineCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="canEdit"
          type="primary"
          :loading="saveloading"
          @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <userList
      :visibles.sync="userDialog.visible"
      :multiple="true"
      :defaultValues="userDialog.defaultLineUsers"
      :branchinnercode="rowBranchinnercode"
      @closeDialog="closeUserDialog"
    ></userList>
  </div>
</template>
<script>
import { getWorkshop, addOrUpdateWorkshop } from "@/api/prodLineMgmt/workshop";
import { listErpProductionLine } from "@/api/prodLineMgmt/productionLine";
import { getNextCodeByModule } from "@/api/common";
import organizationSelect from "@/views/components/organizationSelect";
import { checkPermi } from "@/utils/permission";
export default {
  components: { organizationSelect },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["workshopType"],
  data() {
    return {
      loading: false,
      form: {
        id: null,
        workshopCode: null,
        workshopName: null,
        workshopType: null,
        factoryDeptId: null,
        factoryDeptCode: null,
        factoryDeptName: null,
        productionLineDtos: [],
        workshopHeadUsernames: null,
        workshopHeadRealnames: null,
      },
      productionLineOptions: [],
      rules: {
        workshopCode: [
          { required: true, message: "请输入车间编码", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            message: "支持字母(A-Z、a-z)、数字(0-9)",
            trigger: "blur",
          },
          { max: 32, message: "32个字符以内", trigger: "blur" },
        ],
        workshopName: [
          { required: true, message: "请输入车间名称", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            message: "支持中文、字母(A-Z、a-z)、数字(0-9)和下滑线",
            trigger: "blur",
          },
          { max: 32, message: "32个字符以内", trigger: "blur" },
        ],
        workshopType: [
          { required: true, message: "请选择车间类型", trigger: "change" },
        ],
        factoryDeptCode: [
          { required: true, message: "请选择所属工厂", trigger: "change" },
        ],
        workshopHeadRealnames: [
          { required: true, message: "请选择车间负责人", trigger: "change" },
        ],
      },
      systemNumber: false,
      saveloading: false,
      userDialog: {
        visible: false,
        defaultLineUsers: [],
      },
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    title() {
      if (this.disabled == true) {
        return "车间详情";
      }
      if (!!this.row) {
        return "编辑车间";
      }
      return "新增车间";
    },
    rowBranchinnercode() {
      return this.form.factoryDeptId || null;
    },
    canEdit() {
      // 优先组件参数控制
      if (this.disabled == true) {
        return false;
      }
      // 判断是否有编辑权限
      if (this.row?.id) {
        return checkPermi(["prodLineMgmt:workshop:edit"]);
      }
      return true;
    },
  },
  methods: {
    handleClose() {
      this.saveloading = false;
      this.systemNumber = false;
      this.resetFormData();
    },
    handleOpen() {
      this.getDetail();
    },
    getDetail() {
      if (!this.row?.id) {
        this.resetFormData();
        // 默认获取第一个工厂
        const results = this.getOwnFirstLine();
        this.form.factoryDeptCode = results[0]?.factoryDeptCode || "";
        this.form.factoryDeptId = results[0]?.factoryDeptId || "";
        return;
      }
      this.loading = true;
      getWorkshop(this.row.id)
        .then((res) => {
          if (res.code == 200 && res.data) {
            const {
              id,
              workshopCode,
              workshopName,
              workshopType,
              factoryDeptId,
              factoryDeptCode,
              factoryDeptName,
              productionLineDtos: _productionLineDtos,
              workshopHeadUsernames,
              workshopHeadRealnames,
            } = res.data;
            this.form = {
              id,
              workshopCode,
              workshopName,
              workshopType,
              factoryDeptId,
              factoryDeptCode,
              factoryDeptName,
              productionLineDtos:
                _productionLineDtos?.map((ele) => ele.erpProductionLineCode) ||
                [],
              workshopHeadUsernames,
              workshopHeadRealnames: workshopHeadRealnames || null,
            };
          } else {
            this.resetFormData();
          }
        })
        .catch(() => {
          this.resetFormData();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    openUserDialog() {
      const { workshopHeadUsernames, workshopHeadRealnames } = this.form;

      const _workshopHeadUsernames = workshopHeadUsernames
        ? workshopHeadUsernames.split(",")
        : [];
      const _workshopHeadRealnames = workshopHeadRealnames
        ? workshopHeadRealnames.split(",")
        : [];

      let _defaultLineUsers = [];
      _workshopHeadUsernames.forEach((ele, i) => {
        _defaultLineUsers.push({
          username: ele,
          realname: _workshopHeadRealnames[i],
        });
      });
      this.userDialog.defaultLineUsers = _defaultLineUsers;
      this.userDialog.visible = true;
    },
    closeUserDialog(list) {
      this.form.workshopHeadUsernames = list
        .map((ele) => ele.username)
        .join(",");
      this.form.workshopHeadRealnames = list
        .map((ele) => ele.realname)
        .join(",");
    },
    getProductLines() {
      const factoryDeptCode = this.form.factoryDeptCode;
      if (!factoryDeptCode) {
        this.productionLineOptions = [];
        return;
      }
      const param = { pageNum: 1, pageSize: 2000, query: { factoryDeptCode } };
      listErpProductionLine(param)
        .then((res) => {
          this.productionLineOptions = res.rows || [];
        })
        .catch(() => {
          this.productionLineOptions = [];
        });
    },
    handleSubmit() {
      if (!this.canEdit) {
        return;
      }
      this.saveloading = true;
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          const {
            id,
            workshopCode,
            workshopName,
            workshopType,
            factoryDeptId,
            factoryDeptCode,
            productionLineDtos: _productionLineDtos,
            workshopHeadUsernames,
            workshopHeadRealnames,
          } = this.form;
          const lines = this.productionLineOptions
            .filter((ele) =>
              _productionLineDtos.includes(ele.erpProductionLineCode)
            )
            .map((ele) => ({
              erpProductionLineCode: ele.erpProductionLineCode,
              factoryDeptCode: ele.factoryDeptCode,
            }));
          const param = {
            id,
            workshopCode,
            workshopName,
            workshopType,
            factoryDeptId,
            factoryDeptCode,
            productionLineDtos: lines,
            workshopHeadUsernames,
            workshopHeadRealnames,
          };
          addOrUpdateWorkshop(param)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess(id ? "修改成功！" : "新增成功！");
                this.$emit("submit-success");
                this.dialogVisible = false;
              }
              this.saveloading = false;
            })
            .catch(() => {
              this.saveloading = false;
            });
        } else {
          this.saveloading = false;
        }
      });
    },
    resetFormData() {
      this.$refs.ruleForm?.resetFields();
      this.form = {
        id: null,
        workshopCode: null,
        workshopName: null,
        workshopType: null,
        factoryDeptId: null,
        factoryDeptCode: null,
        factoryDeptName: null,
        productionLineDtos: [],
        workshopHeadUsernames: null,
        workshopHeadRealnames: null,
      };
    },
    handleFactoryDeptCodeChange(selected) {
      this.form.factoryDeptId = selected?.id || null;
      this.form.factoryDeptCode = selected?.code || null;
      // 包含产线联动，清空
      this.form.productionLineDtos = [];
    },
    handleGetCode(value) {
      if (value == true) {
        getNextCodeByModule("WORKSHOP").then((res) => {
          if (res.code == 200) {
            this.form.workshopCode = res.data || null;
            this.$refs.ruleForm.validateField("workshopCode");
          }
        });
      }
    },
  },
  watch: {
    "form.factoryDeptCode": {
      handler() {
        this.getProductLines();
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
  }
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
    .system-num {
      white-space: nowrap;
      margin-left: 10px;
    }
    .el-date-editor.el-input,
    .el-select,
    .el-cascader,
    .factory-select {
      width: 100%;
    }
  }
}
</style>
